package com.spring.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author panxingyu
 *
 * 动态代理——事务处理
 */
@Component
public class ProxyFactory {
    @Autowired
    private TransactionManager transactionManager;
    public Object proxy(final Object o){
        Proxy.newProxyInstance(
                ProxyFactory.class.getClassLoader(),
                o.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //事务处理
                        try {
                            //开启事务
                            transactionManager.begin();
                            Object result = method.invoke(o, args);
                            //提交事务
                            transactionManager.commit();
                            return result;
                        }catch (Exception e){
                            //出现异常，回滚事务
                            transactionManager.rollback();
                            throw new RuntimeException(e);
                        }finally {
                            transactionManager.close();
                        }
                    }
                }
        );
        return o;
    }
}
